<template>
	<page-meta :page-font-size="$store.state.vuex_fontsize+'px'"
		:root-font-size="$store.state.vuex_fontsize+'px'"></page-meta>
	<!-- 作为页面中的某个组件展示 -->
	<view class="pest-container">
		<view class="Variety">
			<view class="pest-title">请选择识别品种</view>
			<view class="crop-title">
				<button v-for="(item, index) in pestlist" :key="index"
					@click="selectChange(item.cropId, item.name, index)"
					:class="cropIndex === index ? 'crop-item' : 'crop-items'">
					<!-- <image :src="stymet(item, index)" mode="" class="crop-img"></image> -->
					{{ item.name }}
				</button>
			</view>
		</view>
		<view class="type">
			请选择虫害识别方式
		</view>
		<view v-if="names !== '请先选择品种'" class="select-upload-type">
			<!-- qipao-but -->
			<button class="min-but upload-type-butone" @click="uploadimg(1)">
				<uni-icons type="images" color="#fff" style="margin-right: 10rpx;"></uni-icons>
				<view style="font-size: 28rpx;">
					本地上传
				</view>
			</button>
			<button class="min-but upload-type-buttwo" @click="uploadimg(2)">
				<uni-icons type="camera" color="#fff" style="margin-right: 10rpx;"></uni-icons>
				<view style="font-size: 28rpx;">
					拍照识别
				</view>
			</button>
		</view>
		<view class="pest-title" style="margin-top.: 10rpx;font-size: 24rpx;color: #757575;">识别结果</view>
		<!-- 识别结果 -->
		<scroll-view scroll-y="true" :style="{height:setcollapseheight() + 'px'}">
			<view class="pest-message">
				<view class="pest-message-greentitle">识别的图片</view>
				<image class="selected-img" :src="nowimageurl" mode="widthFix"></image>
				<view class="pest-message-greentitle">病虫害基础信息</view>
				<view class="pest-message-main newheitiao">
					<view class="zh-table-title">
						<view class="zh-table-th">病虫害类型</view>
						<view class="zh-table-th">相似度</view>
						<view class="zh-table-th">推荐用药</view>
					</view>
					<view v-for="(pestitem, pestindex) in nowallpestlist.similarPDs" :key="pestindex">
						<view class="zh-table-tr">
							<view class="zh-table-td" @click="getallmessage(pestitem, pestindex)">
								<uni-icons type="arrowdown" color="#d7d9db" class="table-td-icon"></uni-icons>
								{{ pestitem.pdName }}
							</view>
							<view class="zh-table-td">{{ pestitem.dconf }}%</view>
							<view class="zh-table-td" @click="getallNsmessage(pestitem, pestindex)">
								<uni-icons type="arrowdown" color="#d7d9db" class="table-td-icon"></uni-icons>
								点击查看
							</view>
						</view>
						<scroll-view :scroll-y="true" class="zhpopstyle" v-if="nowclicklineindex === pestindex">
							<view class="zhpops-item">
								<span style="font-weight: 600;">病虫害种类：</span>
								{{ newallpestmessage.commonNameSort }}
							</view>
							<view class="zhpops-item">
								<span style="font-weight: 600;">种植物种类：</span>
								{{ newallpestmessage.cropName }}
							</view>
							<view v-for="visitem in newallpestmessage.outline" :key="visitem.keyId" class="zhpops-item">
								<view class="zhpops-item-name">{{ visitem.keyName }}</view>
								<view class="zhpops-item-value">{{ visitem.value }}</view>
							</view>
							<view v-for="visitemone in newallpestmessage.preventionAdvice" :key="visitemone.keyId"
								class="zhpops-item">
								<view class="zhpops-item-name">{{ visitemone.keyName }}</view>
								<view class="zhpops-item-value">{{ visitemone.value }}</view>
							</view>
							<!-- <view>种植物种类：{{newallpestmessage.cropName}}</view> -->
							<image :src="newallpestmessage.typicalImg" class="zhpops-img" />
						</scroll-view>
						<scroll-view :scroll-y="true" class="zhpopstyle" v-if="nowclickNslineindex === pestindex">
							<view v-for="(pestNs, peNsindex) in newallNspestmessage" :key="peNsindex"
								class="zhpops-item">
								<view v-if="pestNs.pestcideName" class="zhpops-item-name">
									<span style="font-weight: 600; margin-right: 5rpx;">药品名字：</span>
									{{ pestNs.pestcideName }}
								</view>
								<view v-if="pestNs.pcId" class="zhpops-item-name">
									<span style="font-weight: 600;margin-right: 5rpx;">有效成分编码：</span>
									{{ pestNs.pcId }}
								</view>
								<view v-if="pestNs.registryNumber" class="zhpops-item-name">
									<span style="font-weight: 600;margin-right: 5rpx;">登记证号：</span>
									{{ pestNs.registryNumber }}
								</view>
								<view v-if="pestNs.manufacturer" class="zhpops-item-name">
									<span style="font-weight: 600;margin-right: 5rpx;">生产厂家：</span>
									{{ pestNs.manufacturer }}
								</view>
								<view v-if="pestNs.dosageForm" class="zhpops-item-name">
									<span style="font-weight: 600;margin-right: 5rpx;">剂型：</span>
									{{ pestNs.dosageForm }}
								</view>
								<view v-if="pestNs.content" class="zhpops-item-name">
									<span style="font-weight: 600;margin-right: 5rpx;">含量：</span>
									{{ pestNs.content }}
								</view>
								<view v-if="pestNs.recommendDose" class="zhpops-item-name">
									<span style="font-weight: 600;margin-right: 5rpx;">推荐剂量：</span>
									{{ pestNs.recommendDose }}
								</view>
								<view v-if="pestNs.usageNotice" class="zhpops-item-name">
									<span style="font-weight: 600;margin-right: 5rpx;">用药提示：</span>
									{{ pestNs.usageNotice }}
								</view>
								<view v-if="pestNs.choiseFlag" class="zhpops-item-name">
									<span style="font-weight: 600;margin-right: 5rpx;">严选标记：</span>
									{{ pestNs.choiseFlag === 0 ? '普通' : '严选' }}
								</view>
								<image v-for="(pestNss, peNs) in pestNs.images" :key="peNs" :src="pestNss"
									class="zhpops-img" />
							</view>
							<!-- <view>种植物种类：{{newallpestmessage.cropName}}</view> -->
						</scroll-view>
					</view>
				</view>
			</view>
			<zh-compress ref="wCompress"></zh-compress>
		</scroll-view>
	</view>
</template>

<script>
	import { agrServiceUrl, v } from '@/config/baseUrl.js'
	import zhCompress from '@/components/w-compress/w-compress.vue';
	export default {
		components: {
			zhCompress,
		},
		data() {
			return {
				Authorization: '',//第三方ai识别token
				// 当前点击的行
				nowclicklineindex: '',
				// 令牌
				accessToken: '',
				// 选择的图片地址
				nowimageurl: '',
				// 上传的图片
				uploadimage: '',
				uploadimageurl: '',
				// 识别后返回的图片地址
				nowrespimageurl: '',
				// 当前识别后的基础信息
				nowallpestlist: {
					cropName: '',
					identifyImg: '',
					similarPDs: [
						// {pdName:"0",dconf:'0'}
					]
				},
				CropList: [],
				// 识别后某个虫害类的详细信息
				newallpestmessage: {
					typicalImg: '',
					commonNameSort: '',
					pdName: '',
					preventionAdvice: [], // 防治建议
					outline: [] // 详细介绍
				},
				getDate: '',
				outputDate: '',
				issetoutputDateblack: false,
				names: '水稻',
				cropId: 'SD',
				nowclickNslineindex: '',
				newallNspestmessage: [],
				pestlist: [{
						name: '水稻',
						cropId: 'SD'
					},
					{
						name: '小麦',
						cropId: 'XM'
					},
					{
						name: '桃',
						cropId: 'TAO'
					},
					{
						name: '葡萄',
						cropId: 'PT'
					},
					{
						name: '草莓',
						cropId: 'CM'
					},
					{
						name: '茶',
						cropId: 'CHA'
					}
				],
				cropIndex: 0
			};
		},
		mounted() {
			this.getOauthToken()
			// this.getlipai();
			this.setcollapseheight()
		},
		methods: {
			getOauthToken() {
				uni.request({
					url: 'https://www.cleverplanting.com/ndj-open-ai/oauth/token?client_id=zhongketaida&grant_type=client_credentials&redirect_uri=http%3a%2f%2fwww.zhongketaida.com&client_secret=zhongketaida,rkkj2018',
					method: 'get',
					success: res => {
						if (res.data.code === 0) {
							this.Authorization = "Bearer " + res.data.data.access_token;
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'error'
							})
						}
					},
					fail: err => {
						console.log(err);
					}
				});
			},
			showPicker() {
				this.$refs.treePicker._show();
			},
			//监听选择（ids为数组）
			selectChange(ids, names, index) {
				this.cropIndex = index;
				this.names = names;
				this.cropId = ids;
				// console.log(ids, names);
			},
			// 获取令牌
			getlipai() {
				// 获取令牌
				uni.request({
					url: agrServiceUrl +
						'v3/largeScreen/socializedData/cleverPlanting/getCropList',
					method: 'get',
					header: {
						'V': v
					},
					success: res => {
						if (res.data.code === 1) {
							let data = res.data.data;
							data.forEach(element => {
								this.$set(element, 'cropId', element.cropSortId);
							});
							this.CropList = data;
							this.names = this.CropList[0].cropList[0].name;
							this.cropId = this.CropList[0].cropList[0].cropId;
						}
					}
				});
			},
			// 上传图片 k为模式选择
			uploadimg(k) {
				if (k === 1) {
					uni.chooseImage({
						sourceType: ['album'],
						// sizeType: ['compressed'],
						crop: {
							quality: 100,
							width: 1024,
							height: 1024,
							resize: false
						},
						success: res => {
							this.nowimageurl = res.tempFilePaths[0];
							setTimeout(() => {
								this.getuploadimgurl();
							}, 1000);
						}
					});
				} else {
					uni.chooseImage({
						sourceType: ['camera'],
						sizeType: ['compressed'],
						success: res => {
							this.nowimageurl = res.tempFilePaths[0];
							setTimeout(() => {
								this.getuploadimgurl();
							}, 1000);
						}
					});
				}
			},
			/**
			 * @param {Object} this.uploadimage 图片路径
			 * @param {Object} i 顺序
			 * @description 暂时不用，因为在选择图片的是侯已经压缩一遍了
			 */
			zipimage() {
				let self = this;
				return new Promise(resolve => {
					uni.compressImage({
						src: self.uploadimage,
						quality: 10,
						width: '150px',
						height: '150px',
						success: res => {
							resolve(res.tempFilePath);
						}
					});
				});
			},
			//获取返回的url
			async getuploadimgurl(image) {
				uni.showLoading({
					mask: true,
					title: '上传中...'
				});
				uni.uploadFile({
					url: 'https://www.cleverplanting.com/ndj-open-ai/v1/img-upload/save-discern-img',
					filePath: this.nowimageurl,
					name: 'file',
					header: {
						Authorization: this.Authorization
					},
					success: res => {
						uni.hideLoading();
						console.log(res);
						let data = JSON.parse(res.data);
						if (data.data.url) {
							uni.showToast({
								title: '上传成功',
								icon: 'success'
							});
							this.nowrespimageurl = data.data.url;
							this.shibieimgmet();
						} else {
							uni.showToast({
								title: '图片上传失败',
								icon: 'error'
							});
						}
					},
					fail: err => {
						uni.hideLoading();
						uni.showToast({
							title: '图片上传失败',
							icon: 'error'
						});
					}
				});
			},
			// 识别图片
			shibieimgmet() {
				// 获取病虫害图片
				let params = {
					cropId: this.cropId,
					imgUrl: this.nowrespimageurl
				};
				uni.request({
					url: 'https://www.cleverplanting.com/ndj-open-ai/ndj-api/v1/discern/ai-discern',
					method: 'POST',
					header: {
						Authorization: this.Authorization,
					},
					data: params,
					success: res => {
						console.log(res);
						this.nowallpestlist = res.data.data;
					},
					fail: err => {
						uni.showToast({
							title: '上传失败',
							icon: 'error'
						});
					}
				});
			},
			// 查看图片的信息
			getallmessage(e, i) {
				// console.log(i)
				if (this.nowclicklineindex === i) {
					this.nowclicklineindex = '';
					// this.newallNspestmessage = [];
				} else {
					this.nowclicklineindex = i;
					this.nowclickNslineindex = '';
					this.newallNspestmessage = [];
				}
				let parlist = [];
				parlist.push(e.pdId);
				// 获取病虫害图片
				let params = {
					cropId: this.cropId,
					pdIds: parlist
				};
				uni.request({
					url: 'https://www.cleverplanting.com/ndj-open-ai/ndj-api/v1/pests-diseases/findByPdIds',
					method: 'POST',
					header: {
						Authorization: this.Authorization,
					},
					data: params,
					success: res => {
						console.log(res);
						if (res.data.code === 0) {
							if (res.data.data.length > 0) {
								// this.newallNspestmessage = res.data.data;
								this.newallpestmessage = res.data.data[0];
							} else {
								this.newallpestmessage = {
									typicalImg: '',
									commonNameSort: '',
									pdName: '',
									preventionAdvice: [], // 防治建议
									outline: [] // 详细介绍
								};
								this.newallNspestmessage = [];
								uni.showToast({
									title: '暂无防治建议',
									icon: 'none'
								});
							}
						}
					},
					fail: err => {
						console.log(err);
					}
				});
			},
			getallNsmessage(e, i) {
				// console.log(i)
				if (this.nowclickNslineindex === i) {
					this.nowclickNslineindex = '';
				} else {
					this.nowclickNslineindex = i;
					this.nowclicklineindex = '';
					this.newallpestmessage = {
						typicalImg: '',
						commonNameSort: '',
						pdName: '',
						preventionAdvice: [], // 防治建议
						outline: [] // 详细介绍
					};
				}
				// 获取病虫害图片
				let params = {
					cropId: this.cropId,
					pdId: e.pdId
				};
				uni.request({
					url: 'https://www.cleverplanting.com/ndj-open-ai/ndj-api/v1/pests-diseases/pestcideByPdId',
					method: 'POST',
					header: {
						Authorization: this.Authorization,
					},
					data: params,
					success: res => {
						if (res.data.code === 0) {
							if (res.data.data.length > 0) {
								this.newallNspestmessage = res.data.data;
							} else {
								this.newallpestmessage = {
									typicalImg: '',
									commonNameSort: '',
									pdName: '',
									preventionAdvice: [], // 防治建议
									outline: [] // 详细介绍
								};
								this.newallNspestmessage = [];
								uni.showToast({
									title: '暂无推荐用药',
									icon: 'none'
								});
							}
						}
					},
					fail: err => {
						console.log(err);
					}
				});
			},
			// 关闭弹框
			closezhpop() {
				this.$refs.zhpop.close();
			},
			//--------顶部导航栏方法-----
			//退出系统
			loginout() {
				// #ifdef APP-PLUS
				plus.runtime.quit();
				// #endif
			},
			//返回上一步
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			//压缩图片
			compress(img) {
				// console.log('开始压缩');
				let that = this;
				return new Promise(res => {
					// var localPath = plus.io.convertAbsoluteFileSystem(img);
					plus.io.resolveLocalFileSystemURL(
						img,
						entry => {
							//通过URL参数获取目录对象或文件对象
							entry.file(file => {
								// 可通过entry对象操作图片
								// console.log('压缩前图片信息:' + JSON.stringify(file)); //压缩前图片信息
								if (file.size > 504800) {
									//   如果大于500Kb进行压缩
									plus.zip.compressImage({
											// 5+ plus.zip.compressImage 了解一下，有详细的示例
											src: img, //src: 压缩原始图片的路径
											dst: img
												.replace('.png', '2222.png')
												.replace('.PNG', '2222.PNG')
												.replace('.jpg', '2222.jpg')
												.replace('.JPG', '2222.JPG'),
											width: '40%', //dst: (String 类型 )压缩转换目标图片的路径，这里先在后面原始名后面加一个2222区分一下
											height: '40%', //width,height: (String 类型 )缩放图片的宽度,高度
											quality: 10, //quality: (Number 类型 )压缩图片的质量
											overwrite: true //overwrite: (Boolean 类型 )覆盖生成新文件
											// format:'jpg'   //format: (String 类型 )压缩转换后的图片格式
										},
										event => {
											// console.log('压缩后图片信息:' + JSON.stringify(event)); // 压缩后图片信息
											this.imageInfo = event;
											let newImg = event.target;
											res(newImg); //返回新的图片地址，在uploadFile之前接收
										},
										function(err) {
											// console.log('Resolve file URL failed: ' + err.message);
										}
									);
								} else {
									//else小于500kb跳过压缩，直接返回现有的src
									res(img);
								}
							});
						},
						e => {
							// 返回错误信息
							// console.log('Resolve file URL failed: ' + e.message);
						}
					);
				});
			},
			setcollapseheight() {
				let topheightone = uni.upx2px(136)
				// let newheight = this.customBar + topheightone
				let winHeight = 0
				uni.getSystemInfo({
					success: function(res) {
						winHeight = res.windowHeight
					}
				});
				let oldHeight = uni.upx2px(582)

				winHeight = parseInt(winHeight) - topheightone - oldHeight
				// #ifndef H5
				winHeight = winHeight - 10

				// #endif
				return winHeight
			},
		}
	};
</script>

<style lang="scss" scoped>
	.pest-container {
		width: 680rpx;
		padding: 10rpx;
		font-size: 20rpx;
		line-height: 24px;

		.Variety {
			height: 164rpx;
			background-color: #fff;
			padding: 12px;
			box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.16);
			border-radius: 11px 11px 11px 11px;

			.pest-title {
				font-size: 24rpx;
				color: #757575;
				padding-bottom: 24rpx;
				height: 50rpx;
				line-height: 50rpx;
			}

		}

		.type {
			font-size: 24rpx;
			margin-top: 20rpx;
			color: #757575;
		}
		
		.tree-input {
			width: 70%;
			border-radius: 20rpx;
			padding: 10rpx 20rpx;
			border: 1rpx solid #828485;
			font-size: 25rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;

			.tree-input {
				width: 50%;
			}
		}
	}

	.select-upload-type {
		height: 80rpx;
		display: flex;
		flex-direction: row;
		align-items: center;

		.upload-type-butone {
			width: 180rpx;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			margin-right: 20rpx;
			background: linear-gradient(270deg, #88ACFF 0%, #2165FF 100%);
		}

		.upload-type-buttwo {
			width: 180rpx;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			background: linear-gradient(270deg, #88ACFF 0%, #2165FF 100%);
		}
	}

	.pest-message {
		border-radius: 20rpx;
		background-color: #f5f7f9;

		.pest-message-greentitle {
			color: #002E96;
			font-size: 28rpx;
			font-weight: 600;
		}

		.selected-img {
			width: 660rpx;
			margin-left: 10rpx;
			background-color: #BCD1FF;
		}
	}

	.pest-message-main {
		.zh-table-title {
			width: 680rpx;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 30rpx;
			font-weight: 600;
			background-color: #BCD1FF;
			border: 1px solid #dcdedf00;

			.zh-table-th {
				display: inline-block;
				width: 219rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				white-space: nowrap;
			}

			.zh-table-th:nth-child(1) {
				border-right: 2rpx solid #5ba68f;
			}

			.zh-table-th:nth-child(2) {
				border-right: 2rpx solid #5ba68f;
			}
		}

		.zh-table-tr {
			width: 680rpx;
			height: 60rpx;
			line-height: 60rpx;
			font-size: 26rpx;
			background-color: #fdffff;
			border: 1px solid #dcdedf;
			display: flex;
			align-items: center;
			align-content: center;
			border-top: none;

			.zh-table-td {
				display: inline-block;
				width: 219rpx;
				height: 60rpx;
				line-height: 60rpx;
				text-align: center;
				white-space: nowrap;
				position: relative;

				.table-td-icon {
					left: 10rpx;
					margin-left: 10rpx;
					position: absolute;
				}
			}

			.zh-table-td:nth-child(1) {
				border-right: 2rpx solid #efeef1;
			}

			.zh-table-td:nth-child(2) {
				border-right: 2rpx solid #efeef1;
			}
		}

		.zhpopstyle {
			.zhpops-item {
				font-size: 26rpx;
				margin-top: 18rpx;

				.zhpops-item-name {
					font-weight: 600;
				}
			}
		}
	}

	// 底部黑杠解决办法
	.newheitiao {
		margin-bottom: constant(safe-area-inset-bottom);
		/* 兼容 iOS < 11.2 */
		margin-bottom: env(safe-area-inset-bottom);
		/* 兼容 iOS >= 11.2 */
		padding-bottom: 20rpx;
	}

	.crop-title {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		align-items: center;
		margin-bottom: 10rpx;

		uni-button:after {
			border: 0px solid rgba(0, 0, 0, 0.2);
		}
		
		/deep/ uni-button {
			line-height: 1!important;
		}

		.crop-item {
			// width: 15%;
			width: 120rpx;
			border-radius: 15px 15px 15px 15px;
			margin: 0 4rpx;
			padding: 15rpx 0px;
			background: linear-gradient(270deg, #88ACFF 0%, #2165FF 100%);
			box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.16);
			color: #fff;
			font-size: 28rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.crop-img {
				width: 25rpx;
				height: 25rpx;
				margin-right: 10rpx;
			}
		}

		.crop-items {
			border-radius: 15px 15px 15px 15px;
			display: flex;
			align-items: center;
			width: 120rpx;
			margin: 0 4rpx;
			font-size: 28rpx;
			justify-content: center;
			box-sizing: border-box;
			// border: 1rpx solid #fff;
			box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.16);
			// tr
			padding: 15rpx 0px;

			.crop-img {
				width: 25rpx;
				height: 25rpx;
				margin-right: 10rpx;
			}
		}
	}

</style>